package com.gxc.webcore.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class VelocityUtil {

	private static VelocityEngine velocity;

	/**
	 * 初始化velocity引擎
	 */
	private static void initVelocity() {
		velocity = new VelocityEngine();
		Properties prop = new Properties();
		prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		prop.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		prop.setProperty(Velocity.PARSE_DIRECTIVE_MAXDEPTH, "8");

		// 这里设置加载类路径里的模板，而不是文件系统路径里的模板
		prop.setProperty("file.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		try {
			velocity.init(prop);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析字符串
	 * 
	 * @param str
	 * @param map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String parseString(String str, Map map) {
		String result = null;
		if (velocity == null) {
			initVelocity();
		}
		VelocityContext context = new VelocityContext(map);
		StringWriter writer = new StringWriter();
		try {
			velocity.evaluate(context, writer, "parse_string", str);
			result = new String(writer.getBuffer());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 解析文件
	 * 
	 * @param path
	 * @param map
	 * @return
	 */
	public static String parseFile(String path,
			@SuppressWarnings("rawtypes") Map map) {
		String result = null;
		try {
			File file = new File(path);
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			String str = "";
			while ((line = br.readLine()) != null) {
				line += "\n";
				str += line;
			}
			result = parseString(str, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
